package com.example.moonshine.baidumap.View.Activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLng;
import com.example.moonshine.baidumap.Modle.MsgStaticdata;
import com.example.moonshine.baidumap.R;
import com.github.zackratos.ultimatebar.UltimateBar;

import java.util.ArrayList;
import java.util.List;

public class NavigationActivity extends Activity {


    public LocationClient mLocationClient;
    public MyLocationConfiguration.LocationMode locationMode;
    private MapView mMapView;
    private BaiduMap mBaiduMap;
    Button button;
    private boolean isFirstLocate  = true;
    Double latitudeend;
    Double longiduteend;
    double latitudestart;
    double longidutestart;
    //gro

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        SDKInitializer.initialize(getApplicationContext());
        setContentView(R.layout.navigation_layout);

        UltimateBar.newColorBuilder()
                .statusColor(Color.parseColor("#003768"))       // 状态栏颜色
                .statusDepth(50)                // 状态栏颜色深度
                .build(this)
                .apply();

        mMapView = (MapView) findViewById(R.id.bmapView);
        mBaiduMap = mMapView.getMap();//获取地图实例
        mBaiduMap = mMapView.getMap();
        // 开启定位图层，一定不要少了这句，否则对在地图的设置、绘制定位点将无效
        mBaiduMap.setMyLocationEnabled(true);
        getGpsdata();
        Log.i("tag","经纬度为"+ MsgStaticdata.getGps());
        /*统一申请权限*/
        List<String> permissionList  = new ArrayList<>();
        if(ContextCompat.checkSelfPermission(NavigationActivity.this, Manifest.
                permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED){
            permissionList.add(Manifest.permission.ACCESS_FINE_LOCATION);
        }
        if(ContextCompat.checkSelfPermission(NavigationActivity.this,Manifest.
                permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED){
            permissionList.add(Manifest.permission.READ_PHONE_STATE);
        }
        if(ContextCompat.checkSelfPermission(NavigationActivity.this,Manifest.
                permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED){
            permissionList.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
        }
        if(!permissionList.isEmpty()){
            String [] permissions= permissionList.toArray(new String[permissionList.
                    size()]);
            /*使用ActivityCompat 统一申请权限 */
            ActivityCompat.requestPermissions(NavigationActivity.this,permissions,1);
        }else {
            requestLocation();
        }
        button = findViewById(R.id.btn_search);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    Intent intent = new Intent();
                    intent.setData(Uri.parse("baidumap://map/marker?location="+latitudeend+","+longiduteend+"&title=目的地&content=makeamarker&traffic=on"));
                    startActivity(intent);
                }catch (Exception e)
                {
                    Intent intent = new Intent();
                    intent.setClass(NavigationActivity.this,BaiduActivity.class);
                    startActivity(intent);
                }

            }
        });
    }

    private void requestLocation(){
        initLocation();
        LocationClientOption option = new LocationClientOption();

        option.setScanSpan(5000);//设置发起定位的请求位置时间间隔
        mLocationClient.setLocOption(option);
        mLocationClient.start();
        setEnd();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode){
            case 1:
                if(grantResults.length>0){
                    for (int result: grantResults
                            ) {
                        if(result !=PackageManager.PERMISSION_GRANTED){
                            Toast.makeText(this, "必须同意所有的权限才能使用本程序", Toast.LENGTH_SHORT).show();
                            finish();
                            return;
                        }
                    }
                    requestLocation();
                }else{
                    Toast.makeText(this, "发生了错误", Toast.LENGTH_SHORT).show();
                }
                break;
        }
    }

    private  void initLocation(){

        mLocationClient = new LocationClient(getApplicationContext());
        mLocationClient.registerLocationListener(new BDLocationListener() {
            @Override
            public void onReceiveLocation(BDLocation bdLocation) {

                mBaiduMap.setMyLocationConfiguration(new MyLocationConfiguration(locationMode,true,null));
                StringBuffer correntPosition = new StringBuffer();
                correntPosition.append("经度：").append(bdLocation.getLatitude()).append("\n");
                correntPosition.append("纬度：").append(bdLocation.getLongitude()).append("\n");
                correntPosition.append("国家：").append(bdLocation.getCountry()).append("\n");
                correntPosition.append("省：").append(bdLocation.getProvince()).append("\n");
                correntPosition.append("市：").append(bdLocation.getCity()).append("\n");
                correntPosition.append("区：").append(bdLocation.getDistrict()).append("\n");
                correntPosition.append("街道：").append(bdLocation.getStreet()).append("\n");
                correntPosition.append("门牌号：").append(bdLocation.getStreetNumber()).append("\n");
//                correntPosition.append("定位方式：");
                latitudestart = bdLocation.getLatitude();
                longidutestart = bdLocation.getLongitude();


                if(bdLocation.getLocType() == BDLocation.TypeGpsLocation ||bdLocation.getLocType() == BDLocation.TypeNetWorkLocation) {

                    if (isFirstLocate){
                        LatLng position = new LatLng(bdLocation.getLatitude(),bdLocation.getLongitude());
//                        MapStatus.Builder builder = new MapStatus.Builder();
//                        builder.target(position).zoom(18.0f);
//                        mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
                        isFirstLocate = false;
                    }
                    MyLocationData.Builder  locationBuilder = new MyLocationData.Builder();
                    locationBuilder.latitude(bdLocation.getLatitude());
                    locationBuilder.longitude(bdLocation.getLongitude());
                    MyLocationData locationData = locationBuilder.build();
                    mBaiduMap.setMyLocationData(locationData);
                }
            }

        });
    }

    private void  setEnd(){
        //定义Maker坐标
        final LatLng point = new LatLng(latitudeend,longiduteend);
        //构建Marker图标
        final BitmapDescriptor bitmap = BitmapDescriptorFactory.fromResource(R.mipmap.ic_gps);
        MapStatus.Builder builder = new MapStatus.Builder();
        builder.target(point).zoom(18.0f);
        mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
        //构建MarkerOption，用于在地图上添加Marker
        OverlayOptions option = new MarkerOptions()
                .position(point)
                .icon(bitmap);
        mMapView.getMap().addOverlay(option);
    }

    @Override
    protected void onResume() {
        super.onResume();
        mMapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mMapView.onPause();
    }

    @Override
    protected void onDestroy() {
        //退出时销毁定位
        super.onDestroy();
        mLocationClient.stop();
        mMapView.onDestroy();
        mBaiduMap.setMyLocationEnabled(false);
    }

    @SuppressLint("UseValueOf")
    public void getGpsdata(){
        String[] arr =MsgStaticdata.getGps().split(",");
        String latitude1 =  arr[1];
        String longitude1 =arr[0];
        latitudeend = new Double(latitude1);
        longiduteend = new Double(longitude1);
    }
}
